﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PvfUtilityDemo
{
    public class HttpConn
    {

        public class HttpClientConn
        {
            /// <summary>
            /// Get请求
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static string GetResponse(string url)
            {
                string result = string.Empty;

                using (HttpClient httpClient = new())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = httpClient.GetAsync(url).Result;
                    //statusCode = response.StatusCode.ToString();

                    if (response.IsSuccessStatusCode)
                    {
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                }
                return result;
            }

            /// <summary>
            /// Post请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="postData"></param>
            /// <returns></returns>
            public static string PostResponse(string url, string postData)
            {
                string result = string.Empty;
                //设置Http的正文
                HttpContent httpContent = new StringContent(postData);
                //设置Http的内容标头
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")
                {
                    //设置Http的内容标头的字符
                    CharSet = "utf-8"
                };
                using (HttpClient httpClient = new())
                {
                    //异步Post
                    HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                    //输出Http响应状态码
                    //statusCode = response.StatusCode.ToString();
                    //确保Http响应成功
                    if (response.IsSuccessStatusCode)
                    {
                        //异步读取json
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                }
                return result;
            }

        }
    }
}
